package com.okilo.online.app.fmt

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.okilo.online.app.R
import com.okilo.online.app.act.OkiloAdviceTypeAct
import com.okilo.online.app.act.OkiloPrivacyPolicyAct
import com.okilo.online.app.act.OkiloSettingAct
import com.okilo.online.app.act.OkiloUserLoginAct
import com.okilo.online.app.common.OkiloComFmt
import com.okilo.online.app.configs.OkiloConfigs
import com.okilo.online.app.databinding.OkiloFmtTabMeBinding
import com.okilo.online.app.event.OkiloEventData
import com.okilo.online.app.event.OkiloEventPointType
import com.okilo.online.app.tools.apt.OkiloOnSingleClickListener
import com.okilo.online.app.tools.helper.OkiloConfigCustomerHp
import com.okilo.online.app.tools.helper.OkiloConfigProcessHp
import com.okilo.online.app.tools.helper.OkiloCustomDataHp
import com.okilo.online.app.tools.shared.OkiloSharedHp
import com.okilo.online.app.tools.shared.OkiloSharedKey
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * OkiloLoan
 * @Author wwdeng
 * @CreateTime: 2024/12/10 14:53
 * @Annotation：我的
 */
class OkiloTabMeFmt(): OkiloComFmt() {
    private var _binding: OkiloFmtTabMeBinding? = null

    override val pageName: String = "UserCenter_Page"

    override fun createOkiloContentView(inflater: LayoutInflater): View? {
        _binding = OkiloFmtTabMeBinding.inflate(layoutInflater)
        return _binding?.root
    }

    override fun initializeOkiloViews() {
        getTitleBarManager()
            .setRootBackgroundColor(getColor(R.color.okilo_color_ffeff1f3))
        initOkiloTabMeRefreshView()
    }

    override fun setupOkiloEventListeners() {
        _binding?.okiloTabMePPLayout?.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                val showTitle = getString(R.string.okilo_privacy_policy)
                val linkUrl = OkiloConfigs.OKILO_PP_NIGERIA_LINK
                OkiloPrivacyPolicyAct.Companion.start(requireContext(), showTitle, linkUrl)
            }
        })
        _binding?.okiloTabMeFeedbackLayout?.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                onIntent(OkiloAdviceTypeAct::class.java)
            }
        })
        _binding?.okiloTabMeSettingLayout?.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                onIntent(OkiloSettingAct::class.java)
            }
        })
        _binding?.okiloTabMeLogOutLayout?.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.USER_LOGINOUT)
                //退出登录，需要移除用户保存的信息
                OkiloSharedHp.onOkiloAppOut()
                lifecycleScope.launch {
                    delay(300)
                    onIntent(OkiloUserLoginAct::class.java)
                }
            }
        })
    }

    @SuppressLint("SetTextI18n")
    override fun loadOkiloData() {
        sOkiloTabMeUserName()
        _binding?.textUserMobile?.text = "+${OkiloSharedHp.gOkiloSharedString(OkiloSharedKey.SP_OKILO_TIMEZONE_CODE)} ${OkiloConfigs.gOkiloLoginMobile()}".maskMiddle(4,"*")

        //是否有新版本
        val isUpdate = OkiloConfigCustomerHp.iOkiloReleaseUpdate()
        if (isUpdate){
            _binding?.updateViewPoint?.visibility = View.VISIBLE
        } else {
            _binding?.updateViewPoint?.visibility = View.GONE
        }

        //加载保存自定义数据
        OkiloCustomDataHp.gOkiloAppCustomDataAction()
    }

    /* 初始化刷新 */
    private fun initOkiloTabMeRefreshView() {
        _binding?.okiloTabMeRefreshLayout?.setColorSchemeResources(R.color.okilo_color_theme, R.color.okilo_color_ff6200ee)
        _binding?.okiloTabMeRefreshLayout?.setOnRefreshListener {
            OkiloCustomDataHp.gOkiloAppCustomDataAction()
        }
    }

    /**
     * 设置用户姓名
     */
    private fun sOkiloTabMeUserName(){
        var userName = getString(R.string.okilo_show_app_name)
        val configProcessData = OkiloConfigProcessHp.gOkiloConfigProcessData()
        configProcessData?.let { data ->
            if (data.optString("fullName","").isNotEmpty()){
                userName = data.optString("fullName","")
            }
        }
        _binding?.okiloUserNameText?.text = userName
    }

    fun String.maskMiddle(visibleChars: Int = 4, maskChar: String = "*"): String {
        return when {
            length <= visibleChars * 2 -> this
            else -> {
                val firstPart = substring(0, visibleChars)
                val lastPart = substring(length - visibleChars)
                val mask = maskChar.repeat(4) // 固定4个星号，或者可以用 visibleChars
                "$firstPart$mask$lastPart"
            }
        }
    }

    override fun onOkiloPublishEvent(event: OkiloEventData) {
        super.onOkiloPublishEvent(event)
        when(event.eventType){
            OkiloEventData.TYPE.OKILO_PROCESS_REFRESHED -> {//流程刷新完成
                sOkiloTabMeUserName()
            }
            OkiloEventData.TYPE.OKILO_CUSTOM_DATA_REFRESHED,
            OkiloEventData.TYPE.OKILO_HTTP_REQUEST_ERROR -> {
                hideOkiloLoading()
            }
            else -> {

            }
        }
    }

    override fun hideOkiloLoading() {
        super.hideOkiloLoading()
        _binding?.okiloTabMeRefreshLayout?.isRefreshing = false
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}